package com.zzyl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzyl.base.PageResponse;
import com.zzyl.entity.NursingProject;
import com.zzyl.entity.Reservation;
import com.zzyl.mapper.ReservationMapper;
import com.zzyl.service.ReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.NursingProjectVo;
import com.zzyl.vo.ReservationVo;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

@Service
public class ReservationServiceImpl implements ReservationService {
  @Autowired
  private ReservationMapper reservationMapper;

  @Override
  public Long getCount() {
    Long userId = UserThreadLocal.getUserId();
    return reservationMapper.getCount(userId);
  }


  @Override
  public void addReservation(Reservation reservationDto) {
    Long createBy = UserThreadLocal.getUserId();
    reservationDto.setCreateBy(createBy);
    reservationDto.setStatus(0);
 ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0L,
        java.util.concurrent.TimeUnit.MILLISECONDS,
        new java.util.concurrent.LinkedBlockingQueue<>());
    executor.execute(new Runnable() {
      @Override
      public void run() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 设置预约时间
        reservationDto.setTime(now);
      }
    });
    reservationMapper.addReservation(reservationDto);
  }


  @Override
  public List<ReservationVo> getCountByTime(Long time) {
    // 将时间戳转换为Instant
    Instant instant = Instant.ofEpochMilli(time);
    // 将Instant转换为特定时区的LocalDate
    LocalDate date = instant.atZone(ZoneId.systemDefault()).toLocalDate();
    // 调用mapper层的方法
    return reservationMapper.getCountByTime(date);
  }

  @Override
  public PageResponse<ReservationVo> getByPage(Integer status, Integer pageNum, Integer pageSize) {
    PageHelper.startPage(pageNum, pageSize);
    Page<Reservation> reservations = reservationMapper.selectByPage(status);
    PageResponse<ReservationVo> reservationVoPageResponse = PageResponse.of(reservations, ReservationVo.class);
    return reservationVoPageResponse;
  }

  @Override
  public void cancel(Long id) {
    reservationMapper.cancel(id);
  }

  @Override
  public void expired() {
    reservationMapper.expired();
  }
}
